package team3.tracking.services;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class UDPHandler {
	private DatagramSocket clientSocket = null;
	private int port;
	private InetAddress inetAddress;
	
	public UDPHandler(String address, int port){ //receives the IP address and the port of the Server to which it will connect
		this.port = port;
		try { //set receiver address
			inetAddress = InetAddress.getByName(address);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}
	
	public void start(){ //start the socket
		try {
    		clientSocket = new DatagramSocket();
    	} catch (SocketException e) {
    		e.printStackTrace();
    	}  
	}
	
	public void close(){ //close the socket
		if(clientSocket != null){
			clientSocket.close();
			clientSocket = null;
		}
	}
	
	public void send(byte[] data){
		// send one datagram
		DatagramPacket packet = new DatagramPacket(data, data.length, 
		        									inetAddress, port);
		
		try {
		clientSocket.send(packet);
		} catch (IOException e) {
		e.printStackTrace();
		}
	}
}
